package com.luojing.springcloud.rocketmq;

import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * @author luojing
 * @create 2018/10/23 3:52 PM
 **/
public class SimpleCousumer {
  public static void cousumer() throws Exception{
    // Instantiate with specified consumer group name.
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name");

    // Specify name server addresses.
    consumer.setNamesrvAddr("localhost:9876");

    // Subscribe one more more topics to consume.
    //sql
    consumer.subscribe("TopicTest", MessageSelector.bySql("a between 0 and 3"));
    // Register callback to execute on arrival of messages fetched from brokers.
    consumer.registerMessageListener(new MessageListenerConcurrently() {

      @Override
      public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
          ConsumeConcurrentlyContext context) {
        String a = null;
        try {
          a = new String(msgs.get(0).getBody(), RemotingHelper.DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(),a);
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
      }
    });

    //Launch the consumer instance.
    consumer.start();
    System.out.printf("Consumer Started.%n");
  }

  public static void main(String[] args) throws Exception {
    cousumer();
  }
}
